<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/7/21 16:43
 */

namespace module\chat\logic;

use app\model\Config;
use module\ai\model\Channel;
use module\user\model\User;
use mof\annotation\Inject;
use mof\exception\LogicException;
use mof\interface\UserInterface;
use mof\Logic;
use think\Collection;
use think\db\exception\DbException;

class ConfigLogic extends Logic
{
    #[Inject(Config::class)]
    protected $model;

    /**
     * 获取对话时可用的AI通道
     * @return Collection|null
     */
    public function getChannels($options = []): ?\think\model\Collection
    {
        $ids = config('chat.channel_ids', []);
        try {
            if (!$ids) return null;
            $rows = Channel::where('status', 1)->where('id', 'in', $ids)->select();
            if ($rows->isEmpty()) {
                throw new LogicException('未提供可用的AI通道');
            }
            //提供消费积分信息
            if (!empty($options['consumption'])) {
                $rows->each(function ($row) use ($options) {
                    $row->consumption_score = $this->getConsumptionScore($row, $options['user'] ?? null);
                    $row->append(['consumption_score']);
                });
            } else {
                throw new LogicException('未提供通道消费积分信息');
            }
            return $rows;
        } catch (DbException) {
            return null;
        }
    }


    public function getConsumptionScore(Channel $channel, ?User $user): int
    {
        global $scores;

        //获取需要的费用
        $key = 'user.consumption_' . ($user && $user->isVip ? 'vip' : 'user');
        if (empty($scores[$key])) {
            $scoresRaw = $this->app->config->get($key);
            $scores[$key] = $scoresRaw;
        }
        //从配置中获取对应key的消费金额
        $result = $scores[$key][$channel->id] ?? null;
        if (is_null($result) || trim($result) === '') {
            throw new LogicException(sprintf('未找到[%s]通道消费积分信息', $channel->name));
        } else if (!is_numeric($result) || $result < 0) {
            throw new LogicException(sprintf('消费积分信息[%s]格式错误', $result));
        }

        return intval($result);
    }
}